﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PaperPluginUtilities
{
    public static class ImageUrlParsing
    {
        private static string[] allowedExtensions = new string[] { ".png", ".jpg", ".jpeg", ".ps", ".eps", ".pdf", ".pdf", ".tiff", ".gif" };

        public struct LinkInfo
        {
            public string url;
            public string urlName;
        }

        /// <summary>
        /// Tries to find the best possible image to use for rendering.
        /// </summary>
        /// <param name="pics"></param>
        /// <returns></returns>
        public static LinkInfo GetBestImage(IEnumerable<LinkInfo> pics)
        {
            var result = allowedExtensions.SelectMany(ext =>
            {
                var foundMatches = from p in pics
                                   where GetNormalizedFileExtension(p.url) == ext
                                   select p;
                return foundMatches;
            });
            return result.FirstOrDefault();
        }

        /// <summary>
        /// Attempt to figure out if this url points to a picture or not.
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static bool IsPictureType(string urlString)
        {
            string ext = GetNormalizedFileExtension(urlString);
            return allowedExtensions.Contains(ext);
        }

        public static string GetNormalizedFileExtension(string urlString)
        {
            string ext = Path.GetExtension(urlString.Split('/').Last()).ToLower();
            return ext;
        }
        public static string GetNormalizedFileExtension(this Uri url)
        {
            return GetNormalizedFileExtension(url.OriginalString);
        }

        /// <summary>
        /// Get the name from the URL
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string GetPictureFileName(string urlText)
        {
            return Path.GetFileNameWithoutExtension(urlText.Split('/').Last());
        }
    }
}
